﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using LY.Interface;
using LY.Entity;
using LY.Entity.PageSearch;
using LY.Entity.SearchEntity;
using LY.Entity.Jsons;
using LY.Entity.Entities;

namespace QJ.CMS.Areas.Admin.Controllers
{
    public class RoleController : Controller
    {
        //
        // GET: /Role/

        private IRoleService _rservice;
        private IModuleService _mservice;
        private IUserService _uservice;
        private IMenuService _meservice;
        public RoleController(IRoleService rService, IModuleService mService, IUserService uService, IMenuService _meService)
        {
            _rservice = rService;
            _mservice = mService;
            _uservice = uService;
            _meservice = _meService;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult MenuTree()
        {
            return View();
        }

        public ActionResult RoleTree()
        {
            return View();
        }

        public ActionResult SetRoleModule(int? Id)
        {
            S_Role role = null;
            List<S_Module_EX> mList = null;
            if (Id.HasValue)
            {
                role = _rservice.GetRole(Id.Value);
                mList = _mservice.QueryRoleModuleList(role.ID);
            }
            else
            {
                role = new S_Role();
                mList = _mservice.QueryNewRoleModuleList();
            }
            ViewBag.MList = mList;
            return View(role);
        }

        [HttpPost]
        public JsonResult SaveAuthorization(int? Id)
        {
            JsonSMsg rMsg = new JsonSMsg();

            string nodesID = Request.Form["nodesID"];
            int i = _rservice.GiveAuthorization(nodesID, Id);
            rMsg.Status = i;
            return Json(rMsg);
        }

        [HttpPost]
        public JsonResult SaveRoleUser(int? Id)
        {
            JsonSMsg rMsg = new JsonSMsg();

            string nodesID = Request.Form["nodesID"];
            int i = _rservice.SaveRoleUser(nodesID, Id);
            rMsg.Status = i;
            return Json(rMsg);
        }

        public string GetRole()
        {
            StringBuilder sb = new StringBuilder();
            List<S_Role> list = _rservice.GetAllRoleList();
            sb.Append("[");
            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    sb.Append("{id:" + list[i].ID);
                    sb.Append(",pId:0");
                    sb.Append(",name:'" + list[i].Name + "'");
                    sb.Append(@",isParent:false,icon:'../../assets/css/ztree/img/people16.png'},");
                }
            }
            return sb.ToString().TrimEnd(',') + "]";
        }

        public string GetTopMenu(int? Id)
        {
            if (Id.HasValue)
            {
                //MenuService _mservice = new MenuService();
                StringBuilder sb = new StringBuilder();
                S_Role role = _rservice.GetRole(Id);
                string[] arrayString = null;
                List<C_Menu> Toplist = _meservice.GetUpperMenuList(0);
                sb.Append("[{ id: " + Toplist[0].ID + ", pId: " + Toplist[0].UpperID + ", name: '" + Toplist[0].Name + "', open:true");
                if (role.Authorization != null)
                {
                    arrayString = role.Authorization.ToString().Split(',');
                    if (arrayString.Contains(Toplist[0].ID.ToString()))
                    {
                        sb.Append(",checked:true");
                    }
                }
                sb.Append("},");
                List<C_Menu> list = _meservice.GetUpperMenuList(Toplist[0].ID);
                string isParent = string.Empty;
                if (list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        sb.Append("{id:" + list[i].ID);
                        if (role.Authorization != null)
                        {
                            if (arrayString.Contains(list[i].ID.ToString()))
                            {
                                sb.Append(",checked:true");
                            }
                        }
                        sb.Append(",pId:" + list[i].UpperID);
                        sb.Append(",name:'" + list[i].Name + "'");
                        List<C_Menu> chlist = _meservice.GetUpperMenuList(list[i].ID);
                        if (chlist.Count > 0)
                        {
                            isParent = "true";
                        }
                        else
                        {
                            isParent = "false";
                        }
                        sb.Append(",isParent:" + isParent + "},");
                    }
                }
                return sb.ToString().TrimEnd(',') + "]";
            }
            return string.Empty;
        }

        public string GetTopModule(int? Id)
        {
            if (Id.HasValue)
            {

                //ModuleService _mservice = new ModuleService();
                StringBuilder sb = new StringBuilder();
                S_Role role = _rservice.GetRole(Id);
                string[] arrayString = null;
                List<S_Module> Toplist = _mservice.GetUpperModuleList(0);
                sb.Append("[{ id: " + Toplist[0].ID + ", pId: " + Toplist[0].ParentID + ", name: '" + Toplist[0].Name + "', open:true");
                if (role.Authorization != null)
                {
                    arrayString = role.Authorization.ToString().Split(',');
                    if (arrayString.Contains(Toplist[0].ID.ToString()))
                    {
                        sb.Append(",checked:true");
                    }
                }
                sb.Append("},");
                List<S_Module> list = _mservice.GetUpperModuleList(Toplist[0].ID);
                string isParent = string.Empty;
                if (list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        sb.Append("{id:" + list[i].ID);
                        if (role.Authorization != null)
                        {
                            if (arrayString.Contains(list[i].ID.ToString()))
                            {
                                sb.Append(",checked:true");
                            }
                        }
                        sb.Append(",pId:" + list[i].ParentID);
                        sb.Append(",name:'" + list[i].Name + "'");
                        List<S_Module> chlist = _mservice.GetUpperModuleList(list[i].ID);
                        if (chlist.Count > 0)
                        {
                            isParent = "true";
                        }
                        else
                        {
                            isParent = "false";
                        }
                        sb.Append(",isParent:" + isParent + "},");
                    }
                }
                return sb.ToString().TrimEnd(',') + "]";
            }
            return string.Empty;
        }

        public string GetTopUser(int? Id)
        {
            if (Id.HasValue)
            {
                //UserService _mservice = new UserService();
                StringBuilder sb = new StringBuilder();
                S_Role role = _rservice.GetRole(Id);
                string[] arrayString = null;
                List<S_User> Toplist = _uservice.GetUpperUserList(0);
                sb.Append("[{ id: " + Toplist[0].ID + ", pId: " + Toplist[0].DeptID + ", name: '" + Toplist[0].UserName + "', open:true");
                if (role.Authorization != null)
                {
                    arrayString = role.Authorization.ToString().Split(',');
                    if (arrayString.Contains(Toplist[0].ID.ToString()))
                    {
                        sb.Append(",checked:true");
                    }
                }
                sb.Append("},");
                List<S_User> list = _uservice.GetUpperUserList(Toplist[0].ID);
                string isParent = string.Empty;
                if (list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        sb.Append("{id:" + list[i].ID);
                        if (role.Authorization != null)
                        {
                            if (arrayString.Contains(list[i].ID.ToString()))
                            {
                                sb.Append(",checked:true");
                            }
                        }
                        sb.Append(",pId:" + list[i].DeptID);
                        sb.Append(",name:'" + list[i].UserName + "'");
                        List<S_User> chlist = _uservice.GetUpperUserList(list[i].ID);
                        if (chlist.Count > 0)
                        {
                            isParent = "true";
                        }
                        else
                        {
                            isParent = "false";
                        }
                        sb.Append(",isParent:" + isParent + "},");
                    }
                }
                return sb.ToString().TrimEnd(',') + "]";
            }
            return string.Empty;
        }
        [HttpPost]
        public JsonResult GetData(int? id, int? RoleID)
        {
            //ModuleService _mservice = new ModuleService();
            //MenuService _mservice = new MenuService();
            List<Node> nodeList = new List<Node>();
            S_Role role = _rservice.GetRole(RoleID);
            string[] arrayString = null;
            if (role.Authorization != null)
            {
                arrayString = role.Authorization.ToString().Split(',');
            }
            if (id.HasValue)
            {
                //DataView dv = _mservice.GetMenuView(id.Value);
                List<C_Menu> list = _meservice.GetUpperMenuList(id.Value);
                if (list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        Node node = new Node();
                        if (role.Authorization != null)
                        {
                            if (arrayString.Contains(list[i].ID.ToString()))
                            {
                                node.@checked = true;
                            }
                        }
                        node.id = list[i].ID;
                        node.pId = Convert.ToInt32(list[i].UpperID);
                        node.name = list[i].Name;
                        List<C_Menu> chlist = _meservice.GetUpperMenuList(node.id);
                        if (chlist.Count > 0)
                        {
                            node.isParent = true;
                        }
                        else
                        {
                            node.isParent = false;
                        }
                        nodeList.Add(node);
                    }
                }
            }
            return Json(nodeList);
        }

        [HttpPost]
        public JsonResult GetModuleData(int? id, int? RoleID)
        {
            //ModuleService _mservice = new ModuleService();
            //MenuService _mservice = new MenuService();
            List<Node> nodeList = new List<Node>();
            S_Role role = _rservice.GetRole(RoleID);
            string[] arrayString = null;
            if (role.Authorization != null)
            {
                arrayString = role.Authorization.ToString().Split(',');
            }
            if (id.HasValue)
            {
                //DataView dv = _mservice.GetMenuView(id.Value);
                List<S_Module> list = _mservice.GetUpperModuleList(id.Value);
                if (list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        Node node = new Node();
                        if (role.Authorization != null)
                        {
                            if (arrayString.Contains(list[i].ID.ToString()))
                            {
                                node.@checked = true;
                            }
                        }
                        node.id = list[i].ID;
                        node.pId = Convert.ToInt32(list[i].ParentID);
                        node.name = list[i].Name;
                        List<S_Module> chlist = _mservice.GetUpperModuleList(node.id);
                        if (chlist.Count > 0)
                        {
                            node.isParent = true;
                        }
                        else
                        {
                            node.isParent = false;
                        }
                        nodeList.Add(node);
                    }
                }
            }
            return Json(nodeList);
        }

        [HttpPost]
        public JsonResult GetUserData(int? id, int? RoleID)
        {
            //UserService _mservice = new UserService();
            //ModuleService _mservice = new ModuleService();
            //MenuService _mservice = new MenuService();
            List<Node> nodeList = new List<Node>();
            S_Role role = _rservice.GetRole(RoleID);
            string[] arrayString = null;
            if (role.Authorization != null)
            {
                arrayString = role.Authorization.ToString().Split(',');
            }
            if (id.HasValue)
            {
                //DataView dv = _mservice.GetMenuView(id.Value);
                List<S_User> list = _uservice.GetUpperUserList(id.Value);
                if (list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        Node node = new Node();
                        if (role.Authorization != null)
                        {
                            if (arrayString.Contains(list[i].ID.ToString()))
                            {
                                node.@checked = true;
                            }
                        }
                        node.id = list[i].ID;
                        node.pId = Convert.ToInt32(list[i].DeptID);
                        node.name = list[i].UserName;
                        List<S_User> chlist = _uservice.GetUpperUserList(node.id);
                        if (chlist.Count > 0)
                        {
                            node.isParent = true;
                        }
                        else
                        {
                            node.isParent = false;
                        }
                        nodeList.Add(node);
                    }
                }
            }
            return Json(nodeList);
        }
        class Node
        {
            /// <summary>
            /// 节点编号
            /// </summary>
            public int id
            {
                get;
                set;
            }

            /// <summary>
            /// 父节点编号
            /// </summary>
            public int pId
            {
                get;
                set;
            }

            /// <summary>
            /// 节点名称
            /// </summary>
            public string name
            {
                get;
                set;
            }

            /// <summary>
            /// 是否为父节点
            /// </summary>
            public bool isParent
            {
                get;
                set;
            }

            public bool @checked
            {
                get;
                set;
            }

            ///这里可以继续扩展节点的其他属性
        }

        [HttpPost]
        public JsonResult RoleSave(int? id, int? UpperID, S_Role menu, FormCollection collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                string errmsg = "";
                if (!Validate(menu, out errmsg))
                {
                    rMsg.Status = -1;
                    rMsg.Message = errmsg;
                    return Json(rMsg);
                }
                //if (id.HasValue)
                //{
                //    menu.ID = Convert.ToInt32(id);
                //}
                int ret = _rservice.SaveRole(menu);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Data = ret;
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        private static bool Validate(S_Role menu, out string errmsg)
        {
            errmsg = "";
            if (menu == null)
            {
                errmsg = "参数错误！";
                return false;
            }

            return true;
        }

        public JsonResult RoleList(RoleSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];

            PagedList<S_Role> pList = _rservice.QueryRoleList(search, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<S_Role>(pList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }

        public ActionResult RoleEdit(int? Id)
        {

            S_Role menu = null;
            if (Id.HasValue)
            {
                menu = _rservice.GetRole(Id.Value);
            }
            else
            {
                menu = new S_Role();
            }
            return View(menu);
        }

        public ActionResult GiveAuthorization(int? Id)
        {
            S_Role role = null;
            if (Id.HasValue)
            {
                role = _rservice.GetRole(Id.Value);
            }
            else
            {
                role = new S_Role();
            }
            return View(role);
        }

        public ActionResult SetRoleUser(int? Id)
        {
            S_Role role = null;
            List<S_User_EX> mList = null;
            if (Id.HasValue)
            {
                role = _rservice.GetRole(Id.Value);
                mList = _uservice.QueryRoleUserList(role.ID);
            }
            else
            {
                role = new S_Role();
                mList = _uservice.QueryRoleUserList();
            }
            ViewBag.MList = mList;
            return View(role);
        }

        [HttpPost]
        public ActionResult RoleDelete(int id, FormCollection collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                if (id <= 0)
                {
                    rMsg.Status = -1;
                    rMsg.Message = "参数错误！";
                    return Json(rMsg);
                }

                int ret = _rservice.DeleteS_Role(id);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Data = ret;
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

    }
}
